var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var _limitMenu = system.MENULIMIT.REPORT25;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH + 'report/kpi_analysis';
var _height = $(parent).height()-288,_width = $(parent).width()-202;

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/to_list_sub_dialog',
			data : {multiselect:true},
			width : 450,
			height : 370,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var sp_code = [];
				var sp_name = [];
				for(var i=0;i<selected.length;i++){
					sp_code.push(selected[i].sp_code);
					sp_name.push(selected[i].sp_name);
				}
				$("#shopCode").val(sp_code.join(","));
				$("#shop_name").val(sp_name.join(","));
			},
			cancel:true
		});
	}
}

var handle = {
	formatMoney:function(value){
		if($.trim(value) == '' || isNaN(value)){
			return value;
		}
		return parseFloat(value).toFixed(2); 
	}
};

var THISPAGE = {
    init: function () {
        this.initDom();
        this.initGrid();
        this.initEvent();
    },
    initDom: function () {
        this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");
    },
    initGrid: function () {
        var colModel = [
            {label: "店铺编号", name: 'shop_code', index: 'shop_code', hidden:true},
            {label: "店铺名称", name: 'shop_name', index: 'shop_name', width: 90,
            	cellattr: function(rowId, tv, rawObject, cm, rdata) {return 'id=\'shop_name' + rowId + "\'";}},
            {label: '项目名称',name: 'project_name', index: 'shl_type', width:80, align: 'center'},
            {label: '销售数量',name: 'sellamount', index: '', width:80, align: 'right'},
            {label: '销售金额',name: 'sellmoney', index: '', width:80, align: 'right',formatter: handle.formatMoney},
            {label: '平均折扣',name: 'avg_discount', index: '', width:80, align: 'right',formatter: handle.formatMoney},
            {label: '成本',name: 'costmoney', index: '', width:80, align: 'right',formatter: handle.formatMoney},
            {label: '毛利润',name: 'profits', index: '', width:80, align: 'right',formatter: handle.formatMoney},
            {label: '会员消费',name: 'sellmoney_vip', index: '', width:80, align: 'right',formatter: handle.formatMoney},
            {label: '会员占比(%)',name: 'sellmoney_vip_proportion', index: '', width:80, align: 'right',formatter: handle.formatMoney},
            {label: '进店人数',name: 'comeamount', index: '', width:80, align: 'right'},
            {label: '接待人数',name: 'receiveamount', index: '', width:80, align: 'right'},
            {label: '试穿人数',name: 'tryamount', index: '', width:80, align: 'right'},
            {label: '成交单数',name: 'dealcount', index: '', width:80, align: 'right'},
            {label: '连带率',name: 'joint_rate', index: '', width:80, align: 'right',formatter: handle.formatMoney},
            {label: '开卡人数',name: 'vipcount', index: '', width:80, align: 'right'},
            {label: '新增储值卡',name: 'cardcount', index: '', width:80, align: 'right'},
            {label: '平均件单价',name: 'avg_price', index: '', width:80, align: 'right',formatter: handle.formatMoney},
            {label: '平均客单价',name: 'avg_sellprice', index: '', width:80, align: 'right',formatter: handle.formatMoney}
        ];
        $('#grid').jqGrid({
            loadonce: true, 
            datatype: 'local',
            width: _width,
			height: _height,
            gridview: true,
            onselectrow: false,
            colModel: colModel,
            rownumbers: true,//行号
            pgbuttons:true,
            recordtext: '{0} - {1} 共 {2} 条',
            rowNum: -1,//每页条数
            cmTemplate: {sortable:false,title:false},
            shrinkToFit: false,//表格是否自动填充
            footerrow: true,
            userDataOnFooter: true,
            jsonReader: {
            	root: 'data.list',
            	userdata: 'data.userData',
                repeatitems: false,
                id: 'id'
            },
            loadComplete: function (data) {
            	THISPAGE.Merger2('shop_name');
            	var ids = $("#grid").getDataIDs();
            	var cols = [
		            'sellamount','sellmoney','avg_discount','costmoney','profits','sellmoney_vip','sellmoney_vip_proportion',
		            'comeamount','receiveamount','tryamount','dealcount','joint_rate','vipcount','cardcount','avg_price','avg_sellprice'
	            ];
            	for(var i=0;i<ids.length;i++){
            		if(i % 2 == 1){
            			continue;
            		}
            		var thisData = $("#grid").jqGrid('getRowData', ids[i]);
            		var lastData = $("#grid").jqGrid('getRowData', ids[i+1]);
            		
            		for(var j=0;j<cols.length;j++){
            			var key = cols[j];
            			if(parseFloat(thisData[key]) > parseFloat(lastData[key])){
                			$("#grid").setCell(ids[i], key,thisData[key], { color: 'blue' });
                        	$("#grid").setCell(ids[i+1], key,lastData[key], { color: 'blue' });
                		}else if(parseFloat(thisData[key]) < parseFloat(lastData[key])){
                			$("#grid").setCell(ids[i], key,thisData[key], { color: 'red' });
                        	$("#grid").setCell(ids[i+1], key,lastData[key], { color: 'red' });
                		}
            		}
            	}
            }
        });
    },
    Merger2:function (CellName) {
        //得到显示到界面的id集合
        var mya = $("#grid").getDataIDs();
        var length = mya.length;
        for (var i = 0; i < length; i++) {
            var before = $("#grid").jqGrid('getRowData', mya[i]);
            if(i%2==0){
            	$("#" + CellName + "" + mya[i] + "").attr("rowspan", 2);
            }else{
            	$("#grid").setCell(mya[i], CellName, '', { display: 'none' });
            }
        }
    },
    initParam:function(){
    	var params = '';
		params += 'begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&shopCode='+$("#shopCode").val();
		return params;
    },
    reloadData: function (data) {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl + "?" + THISPAGE.initParam()}).trigger("reloadGrid");
    },
    reset:function(){
		$("#shop_name").val("");
		$("#shopCode").val("");
		THISPAGE.$_date.setValue(0);
	},
    initEvent: function () {
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
    }
}
THISPAGE.init();